#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using FreeOnlineApplication.Class.Repository;
using FreeOnlineApplication.Class.Entity;

#endregion

namespace FreeOnlineApplication
{
    public partial class LoginForm : Form
    {
        UserRepository r_userRep;
        UnitRepository r_unitRep;
        IMainForm m_mainform = null;

        public LoginForm(IMainForm m)
        {
            InitializeComponent();
            r_userRep = new UserRepository(m.Connection);
            r_unitRep = new UnitRepository(m.Connection);
            m_mainform = m;
            textBoxUnitCode.Focus();
        }

        private void buttonLogin_Click(object sender, EventArgs e)
        {
            try
            {
                string userCode = textBoxCode.Text;
                string password = textBoxPassword.Text;
                //int unit = Convert.ToInt32(numericUpDownUnitID.Value);

                Unit unt = r_unitRep.GetByCode(textBoxUnitCode.Text.Trim());
                if (unt == null)
                {
                    labelMessage.Text = "Invalid Company";
                    textBoxCode.SelectAll();
                    return;
                }
                User user = r_userRep.GetByCode(userCode, unt.ID);
                if (user == null)
                {
                    labelMessage.Text = "Invalid User";
                    textBoxCode.SelectAll();
                    return;
                }
                if (user.PASSWORD != password)
                {
                    labelMessage.Text = "Invalid password";
                    textBoxPassword.SelectAll();
                    return;
                }
                m_mainform.CurrentUser = user;
                m_mainform.CurrentUnit = r_unitRep.GetById(unt.ID);
                m_mainform.EnableSplitContainer();
                this.Close();
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            RegisterForm frm = new RegisterForm(m_mainform);
            frm.ShowDialog();
        }
    }
}